'use client'; import { use, useCallback, useEffect, useState } from 'react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { type BtcVault, SCRIPT_TYPES, NETWORKS, formatBtc, parseBtc, isValidAddress, descriptor, multisigConfigFile, walletPolicy, deriveAddress, } from '../../../../lib/btc/core'; import { scanVault, attachPrevTxs, feeRates, broadcast, history, type ScanResult, type TxSummary } from '../../../../lib/btc/esplora'; import { buildPsbt, combine, psbtFromBytes, parsePsbt, signatureStatus, finalize, summarize } from '../../../../lib/btc/psbt'; import { getVault, saveVault, deleteVault, listPsbts, savePsbt, deletePsbt, newId, download, type PendingPsbt } from '../../../../lib/store'; import { useStore } from '../../../../lib/useStore'; import { useAction, Btn, Err, Copy, QR, FileButton, SigBar, short } from '../../../../components/ui'; import { base64 } from '@scure/base'; type Tab = 'overview' | 'send' | 'pending' | 'addresses' | 'settings'; export default function BtcVaultPage({ params }: { params: Promise<{ id: string }> }) { const { id } = use(params); const vault = useStore(() => getVault(id), [id]) as BtcVault | undefined; const [tab, setTab] = useState('overview'); const [scan, setScan] = useState(null); const [txs, setTxs] = useState([]); const [progress, setProgress] = useState(0); const { busy, error, run } = useAction(); const refresh = useCallback(() => { if (!vault) return; run('scan', async () => { const s = await scanVault(vault, setProgress); setScan(s); setTxs(await history(vault, s.addresses)); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [vault?.id]); useEffect(() => { refresh(); }, [refresh]); if (vault === undefined) return

Loading…

; if (!vault || vault.kind !== 'btc') return

Vault not found. Back to vaults

; const net = NETWORKS[vault.network]; return ( <>
Vaults / {vault.name}
{SCRIPT_TYPES[vault.scriptType].label} · {net.label}

{vault.name}

{vault.m}-of-{vault.cosigners.length}: {vault.cosigners.map((c) => c.name).join(' · ')}

{busy === 'scan' ? `Scanning ${progress}…` : 'Refresh'}
{(['overview', 'send', 'pending', 'addresses', 'settings'] as Tab[]).map((t) => ( ))}
setTab('pending')} /> {tab === 'overview' && } {tab === 'send' && setTab('pending')} />} {tab === 'pending' && } {tab === 'addresses' && } {tab === 'settings' && } ); } /** Banner linking a vault to the one that replaces it (signer / threshold change). */ function Migration({ vault, scan, onCreated }: { vault: BtcVault; scan: ScanResult | null; onCreated: () => void }) { const next = useStore(() => (vault.migratedTo ? getVault(vault.migratedTo) : undefined), [vault.migratedTo]) as BtcVault | undefined; const prev = useStore(() => (vault.migratedFrom ? getVault(vault.migratedFrom) : undefined), [vault.migratedFrom]) as BtcVault | undefined; const { busy, error, run } = useAction(); const unit = vault.network === 'mainnet' ? 'BTC' : 'tBTC'; if (prev && prev.kind === 'btc') { return (

This vault replaces {prev.name} ({prev.m}-of-{prev.cosigners.length} → {vault.m}-of-{vault.cosigners.length}). Open the old vault to move its funds here. Before depositing, back up this vault's new descriptor under Settings.

); } if (!next || next.kind !== 'btc') return null; const balance = scan ? scan.confirmed + scan.unconfirmed : null; const transfer = () => run('migrate', async () => { if (!scan) throw new Error('Wait for the balance scan to finish.'); if (!scan.utxos.length) throw new Error('This vault has no coins to move.'); const to = deriveAddress(next, 0, 0).address; const rates = await feeRates(vault); const utxos = await attachPrevTxs(vault, scan.utxos); const res = buildPsbt(vault, { recipients: [{ address: to, amount: 0n }], sendMax: true, feeRate: rates.halfHourFee, utxos, change: scan.nextChange }); const out = summarize(vault, res.psbt).outputs.find((o) => !o.isChange)!; if (out.address !== to) throw new Error('Destination mismatch; not creating the proposal.'); if (!confirm(`Move the whole balance to the new vault "${next.name}"?\n\n${formatBtc(out.amount)} ${unit}\nto ${to}\nnetwork fee ${formatBtc(res.fee)} ${unit} (${rates.halfHourFee} sat/vB)\n\nThis needs ${vault.m} signatures from the current cosigners.`)) return; savePsbt(vault.id, { id: newId(), title: `Move all funds to ${next.name} (${next.m}-of-${next.cosigners.length})`, psbt: res.psbt, createdAt: Date.now() }); onCreated(); }); return (
Being replaced by {next.name} ({vault.m}-of-{vault.cosigners.length} → {next.m}-of-{next.cosigners.length}).{' '} {balance === null ? 'Checking balance…' : balance === 0n ? 'This vault is empty, so the change is complete. Do not deposit here any more.' : <>It still holds {formatBtc(balance)} {unit}. Back up the new vault's descriptor first, then create the transfer and collect {vault.m} signatures as usual.} {balance !== null && balance > 0n && (
Create transfer to new vault Destination: {short(deriveAddress(next, 0, 0).address, 10)} (new vault, receive #0)
)}
); } function Overview({ vault, scan, txs }: { vault: BtcVault; scan: ScanResult | null; txs: TxSummary[] }) { const net = NETWORKS[vault.network]; const unit = vault.network === 'mainnet' ? 'BTC' : 'tBTC'; const recv = scan?.nextReceive ?? deriveAddress(vault, 0, 0); const { busy, error, run } = useAction(); const [shown, setShown] = useState(null); const hmacs = vault.ledgerHmacs || {}; const canLedger = !!walletPolicy(vault) && Object.keys(hmacs).length > 0; return ( <>
{scan ? formatBtc(scan.confirmed) : '…'}Confirmed {unit}
{scan ? formatBtc(scan.unconfirmed) : '…'}Pending {unit}
{scan ? scan.utxos.length : '…'}Coins (UTXOs)

Receive

Address #{recv.index}. Use a fresh address for every deposit.

{recv.address}

{canLedger && ( run('show', async () => { const { ledgerShowAddress } = await import('../../../../lib/hw/ledger'); const a = await ledgerShowAddress(vault, hmacs, 0, recv.index); if (a !== recv.address) throw new Error(`MISMATCH! Ledger shows ${a}. Do not deposit.`); setShown(a); })}>Verify on Ledger )}
{shown &&

Ledger shows the same address ✓

}
{!canLedger &&

Tip: before large deposits, verify the address on a hardware wallet. For a Ledger cosigner, register the vault under Settings; other devices can import the configuration file.

}

Recent activity

{!txs.length &&

{scan ? 'No transactions yet.' : 'Loading…'}

} {txs.slice(0, 12).map((t) => ( ))}
{short(t.txid)} {t.confirmed ? (t.time ? new Date(t.time * 1000).toLocaleDateString() : '') : pending} {t.delta > 0n ? '+' : ''}{formatBtc(t.delta)}
); } function Send({ vault, scan, onCreated }: { vault: BtcVault; scan: ScanResult | null; onCreated: () => void }) { const [to, setTo] = useState(''); const [amount, setAmount] = useState(''); const [max, setMax] = useState(false); const [fee, setFee] = useState(''); const [rates, setRates] = useState> | null>(null); const [title, setTitle] = useState(''); const { busy, error, run } = useAction(); useEffect(() => { feeRates(vault).then((r) => { setRates(r); setFee(String(r.halfHourFee)); }); }, [vault]); const unit = vault.network === 'mainnet' ? 'BTC' : 'tBTC'; const create = () => run('build', async () => { if (!scan) throw new Error('Wait for the balance scan to finish.'); if (!isValidAddress(to, vault.network)) throw new Error(`Not a valid ${NETWORKS[vault.network].label} address.`); const utxos = await attachPrevTxs(vault, scan.utxos); const res = buildPsbt(vault, { recipients: [{ address: to.trim(), amount: max ? 0n : parseBtc(amount) }], sendMax: max, feeRate: Number(fee), utxos, change: scan.nextChange, }); const sum = summarize(vault, res.psbt); const out = sum.outputs.find((o) => !o.isChange)!; if (!confirm(`Create payment proposal?\n\nPay ${formatBtc(out.amount)} ${unit}\nto ${out.address}\nnetwork fee ${formatBtc(res.fee)} ${unit} (${fee} sat/vB, ~${res.vsize} vB)\n\nNothing is sent until ${vault.m} cosigners sign.`)) return; savePsbt(vault.id, { id: newId(), title: title.trim() || `Pay ${formatBtc(out.amount)} ${unit} to ${short(out.address)}`, psbt: res.psbt, createdAt: Date.now() }); onCreated(); }); return (

New payment proposal

This creates an unsigned transaction (PSBT). It is sent only after {vault.m} of {vault.cosigners.length} cosigners sign it on their own devices.

{rates && Fee presets:} {rates && ([['Fast', rates.fastestFee], ['30 min', rates.halfHourFee], ['1 h', rates.hourFee], ['Economy', rates.economyFee]] as const).map(([l, r]) => ( ))}

Available: {scan ? `${formatBtc(scan.confirmed + scan.unconfirmed)} ${unit}` : 'scanning…'}

Create proposal
); } function Pending({ vault, onBroadcast }: { vault: BtcVault; onBroadcast: () => void }) { const list = useStore(() => listPsbts(vault.id), [vault.id]) ?? []; const { error, run } = useAction(); return ( <>

Share each PSBT file with your cosigners, or sign right here with a connected Ledger or Trezor. Import signed copies to merge signatures.

run('imp', () => { const tx = psbtFromBytes(b); const psbt = base64.encode(tx.toPSBT(0)); const existing = listPsbts(vault.id).find((p) => parsePsbt(p.psbt).id === tx.id); if (existing) savePsbt(vault.id, { ...existing, psbt: combine(existing.psbt, [tx]) }); else { summarize(vault, psbt); savePsbt(vault.id, { id: newId(), title: `Imported ${name}`, psbt, createdAt: Date.now() }); } })}>Import PSBT
{!list.length &&

No pending proposals. Create one under Send.

} {[...list].sort((a, b) => b.createdAt - a.createdAt).map((p) => )} ); } function PsbtCard({ vault, p, onBroadcast }: { vault: BtcVault; p: PendingPsbt; onBroadcast: () => void }) { const { busy, error, run } = useAction(); const [paste, setPaste] = useState(''); const unit = vault.network === 'mainnet' ? 'BTC' : 'tBTC'; let sum, st; try { sum = summarize(vault, p.psbt); st = signatureStatus(vault, p.psbt); } catch (e: any) { return

Unreadable PSBT: {e.message}

; } const have = Math.min(...st.perInput); const merge = (txs: ReturnType[]) => savePsbt(vault.id, { ...p, psbt: combine(p.psbt, txs) }); const net = NETWORKS[vault.network]; return (

{p.title}

{p.broadcast ? 'Broadcast' : st.complete ? 'Ready to broadcast' : `${have} of ${vault.m} signatures`}
{sum.outputs.map((o, i) => ( ))}
{o.isChange ? change → vault : Pay}{o.address}{formatBtc(o.amount)} {unit}
Network fee{formatBtc(sum.fee)} {unit}

Signed by: {vault.cosigners.map((c) => {c.name})}

{p.broadcast ? (

Broadcast as {short(p.broadcast, 10)}

) : ( <>
{walletPolicy(vault) && ( run('ledger', async () => { const { ledgerSignPsbt } = await import('../../../../lib/hw/ledger'); const r = await ledgerSignPsbt(vault, p.psbt, vault.ledgerHmacs || {}); merge([parsePsbt(r.psbt)]); })}>Sign with Ledger )} {vault.scriptType !== 'p2tr' && ( run('trezor', async () => { const { trezorSignPsbt } = await import('../../../../lib/hw/trezor'); const r = await trezorSignPsbt(vault, p.psbt); merge([parsePsbt(r.psbt)]); })}>Sign with Trezor )} run('file', () => merge([psbtFromBytes(b)]))}>Add signed file {st.complete && ( run('send', async () => { const f = finalize(p.psbt); if (!confirm(`Broadcast this transaction to the ${net.label} network? This cannot be undone.`)) return; const txid = await broadcast(vault, f.hex); savePsbt(vault.id, { ...p, broadcast: txid || f.txid }); onBroadcast(); })}>Finalize & broadcast )}